<?php

/**
 * 云信短信
 */
class Winner
{
    private $domain;
    private $userCode;
    private $userPass;
    private $erroCode;

    public function __construct() {
        $this->domain='http://118.178.116.15/winnerrxd/api/trigger/SendMsg';
        $this->userCode='TSWRYJ';
        $this->userPass='KzuR23Ky';
        $this->erroCode=[
            -1=>'应用程序错误',
            -3=>'用户名或密码错误',
            -4=>'短信内容和备案的模板不一样',
            -5=>'签名不正确',
            -7=>'余额不足',
            -8=>'无可用通道或不在通道时间范围',
            -9=>'无效号码',
            -10=>'签名内容不符合长度',
            -11=>'用户有效期过期',
            -12=>'黑名单',
            -16=>'接口请求过于频繁，余额接口 5s 秒一次，其他接口适当调整',
            -17=>'非法 IP',
            -18=>'Msg 内容格式错误',
            -19=>'短信数量错误,小于 1 /大于 500(个性化)/大于 1000（群发）',
            -20=>'号码错误或者黑名单',
            -23=>'解密失败',
            -24=>'短信包含用户敏感信息',
            -25=>'用户被冻结',
            -26=>'无效数据',
            -27=>'请求参数错误',
            -28=>'无效数据',
            -41=>'指定短信模板类型错误或短信类型参数错误',
            -44=>'自定义扩展号不符合规则（1-16 位数字）',
            -46=>'用户黑名单',
            -47=>'系统黑名单',
            -48=>'号码超频拦截',
            -51=>'超过设置的每月短信条数的限制',
            -54=>'短信包含系统敏感信息',
        ];
    }

    /**
     * 发送短信
     */
    public function send($phone, $content)
    {
        $url = $this->domain;
        $field['userCode'] = $this->userCode;
        $field['userPass'] = $this->userPass;
        $field['DesNo']    = $phone;
        $field['Msg']      = $content;
        $data              = $field;
        $response =  $this->curl_post($url, $data, ['Content-Type:application/x-www-form-urlencoded']);

        if (preg_match('%(<string .*?>(.*?)</string>)%i', $response, $regs)) {
            $result = (int) $regs['2'];
            if ($result > 0) {
                return ['code'=>1,'msg'=>'success','data'=>$response];
            }else{
                $msg = isset($this->erroCode[$result])?$this->erroCode[$result]:'未知错误'.$result;
                return ['code'=>0,'msg'=>$msg,'data'=>$response];
            }
        }else{
            return ['code'=>0,'msg'=>'请求错误','data'=>$response];
        }
    }

    public function curl_post($url, $post_data, $header = [''])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}
